"""
Assessment Plan API 路由
提供业务系统评估计划表的HTTP接口
"""
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional
from uuid import UUID

from db.session import get_db
from schemas.assessmentPlan import (
    AssessmentPlanCreate,
    AssessmentPlanUpdate,
    AssessmentPlanResponse,
    AssessmentPlanPagination
)
from core import assessmentPlan as assessment_plan_service
from log import log_api, log_error

router = APIRouter(
    prefix="/assessment-plans",
    tags=["assessment-plans"],
    responses={404: {"description": "Assessment plan not found"}},
)

@router.get("/", response_model=AssessmentPlanPagination)
async def get_assessment_plans(
    name: Optional[str] = None,
    status: Optional[str] = None,
    assessment_type: Optional[str] = None,
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=100),
    db: AsyncSession = Depends(get_db)
) -> AssessmentPlanPagination:
    """
    获取评估计划列表，支持分页和过滤。
    
    Args:
        name: 按业务系统名称过滤（可选）
        status: 按状态过滤（可选）
        assessment_type: 按评估类型过滤（可选）
        skip: 跳过的记录数
        limit: 返回的最大记录数
        db: 数据库会话依赖
        
    Returns:
        分页评估计划列表
    """
    log_api(f"Getting assessment plans with filters: name={name}, status={status}, assessment_type={assessment_type}", 
           module="router.assessmentPlan")
    
    # 构建过滤条件
    filters = {}
    if name:
        filters["name"] = name
    if status:
        filters["status"] = status
    if assessment_type:
        filters["assessment_type"] = assessment_type
    
    return await assessment_plan_service.get_assessment_plans(
        db=db, skip=skip, limit=limit, filters=filters
    )

@router.get("/{plan_id}", response_model=AssessmentPlanResponse)
async def get_assessment_plan(
    plan_id: UUID,
    db: AsyncSession = Depends(get_db)
) -> AssessmentPlanResponse:
    """
    根据ID获取特定评估计划。
    
    Args:
        plan_id: 评估计划ID
        db: 数据库会话依赖
        
    Returns:
        评估计划详情
        
    Raises:
        HTTPException: 当评估计划不存在时
    """
    log_api(f"Getting assessment plan with ID: {plan_id}", module="router.assessmentPlan")
    
    plan = await assessment_plan_service.get_assessment_plan(db=db, plan_id=plan_id)
    if plan is None:
        log_error(f"Assessment plan with ID {plan_id} not found", module="router.assessmentPlan")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Assessment plan with ID {plan_id} not found"
        )
        
    return plan

@router.post("/", response_model=AssessmentPlanResponse, status_code=status.HTTP_201_CREATED)
async def create_assessment_plan(
    plan: AssessmentPlanCreate,
    db: AsyncSession = Depends(get_db)
) -> AssessmentPlanResponse:
    """
    创建新的评估计划。
    
    Args:
        plan: 评估计划数据
        db: 数据库会话依赖
        
    Returns:
        创建的评估计划
    """
    log_api(f"Creating assessment plan: {plan.name}", module="router.assessmentPlan")
    
    return await assessment_plan_service.create_assessment_plan(db=db, plan_data=plan)

@router.put("/{plan_id}", response_model=AssessmentPlanResponse)
async def update_assessment_plan(
    plan_id: UUID,
    plan: AssessmentPlanUpdate,
    db: AsyncSession = Depends(get_db)
) -> AssessmentPlanResponse:
    """
    更新现有评估计划。
    
    Args:
        plan_id: 评估计划ID
        plan: 更新的评估计划数据
        db: 数据库会话依赖
        
    Returns:
        更新后的评估计划
        
    Raises:
        HTTPException: 当评估计划不存在时
    """
    log_api(f"Updating assessment plan with ID: {plan_id}", module="router.assessmentPlan")
    
    updated_plan = await assessment_plan_service.update_assessment_plan(
        db=db, plan_id=plan_id, plan_data=plan
    )
    
    if updated_plan is None:
        log_error(f"Assessment plan with ID {plan_id} not found for update", module="router.assessmentPlan")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Assessment plan with ID {plan_id} not found"
        )
        
    return updated_plan

@router.delete("/{plan_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_assessment_plan(
    plan_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    删除评估计划。
    
    Args:
        plan_id: 评估计划ID
        db: 数据库会话依赖
        
    Raises:
        HTTPException: 当评估计划不存在时
    """
    log_api(f"Deleting assessment plan with ID: {plan_id}", module="router.assessmentPlan")
    
    success = await assessment_plan_service.delete_assessment_plan(db=db, plan_id=plan_id)
    
    if not success:
        log_error(f"Assessment plan with ID {plan_id} not found for deletion", module="router.assessmentPlan")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"Assessment plan with ID {plan_id} not found"
        )
    
    # 204 No Content 响应不包含响应体
